package app.socket.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Set;

public class NIOClient implements Runnable {
	private ByteBuffer sBuffer = ByteBuffer.allocate(1024);
	private ByteBuffer rBuffer = ByteBuffer.allocate(1024);
	private InetSocketAddress SERVER;
	private Selector selector;
	private SocketChannel client;
	private String receiveText;
	private String sendText;
	private int count = 0;

	public NIOClient(int port) {
		SERVER = new InetSocketAddress("localhost", port);
		init();
	}

	public void init() {
		try {
			SocketChannel socketChannel = SocketChannel.open();
			socketChannel.configureBlocking(false);
			selector = Selector.open();
			socketChannel.register(selector, SelectionKey.OP_CONNECT);
			socketChannel.connect(SERVER);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void handle(SelectionKey selectionKey) throws IOException {
		if (selectionKey.isConnectable()) {
			client = (SocketChannel) selectionKey.channel();
			if (client.isConnectionPending()) {
				client.finishConnect();
				System.out.println("connect success !");
//				sBuffer.clear();
//				sBuffer.put((new Date().toLocaleString() + " connected!").getBytes());
//				sBuffer.flip();
//				client.write(sBuffer);
				new Thread() {
					@Override
					public void run() {
						for(int i=1 ; i<4;i++) {
							try {
//								sBuffer.clear();
//								InputStreamReader input = new InputStreamReader(System.in);
//								BufferedReader br = new BufferedReader(input);
//								sendText = br.readLine();
								sendText = i+ "";
//								sBuffer.put(sendText.getBytes());
//								sBuffer.flip();
//								client.write(sBuffer);
								client.write(ByteBuffer.wrap((i+"").getBytes()));
//								socket.getSocketChannel().write(ByteBuffer.wrap(new String("我们测试socket写东西").getBytes()));
							} catch (IOException e) {
								e.printStackTrace();
								break;
							}
						}
					}
				}.start();
			}
			client.register(selector, SelectionKey.OP_READ);
		} 
		else if (selectionKey.isReadable()) {
			client = (SocketChannel) selectionKey.channel();
			rBuffer.clear();
			count = client.read(rBuffer);
			if (count > 0) {
				receiveText = new String(rBuffer.array(), 0, count);
				System.out.println(receiveText);
				client = (SocketChannel) selectionKey.channel();
				client.register(selector, SelectionKey.OP_READ);
			}
		}
	}

	public void run() {
		try {
			while (true) {
				selector.select();
				Set<SelectionKey> keySet = selector.selectedKeys();
				for (final SelectionKey key : keySet) {
					handle(key);
				}
				keySet.clear();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		// 创建NIOClient
		NIOClient client1 = new NIOClient(8888);
		new Thread(client1).start();
//		NIOClient client2 = new NIOClient(7777);
//		new Thread(client2).start();
		// NIOClient client3 = new NIOClient(7778);
		// new Thread(client3).start();
		// NIOClient client4 = new NIOClient(7777);
		// new Thread(client4).start();
	}
}